package com.xu.springcloud.controller;

// import com.netflix.discovery.DiscoveryClient;
import com.xu.springcloud.entities.CommonResult;
import com.xu.springcloud.entities.Payment;
import com.xu.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Slf4j
@RestController
public class PaymentController {

    @Autowired
    PaymentService paymentService;
    @Value("${server.port}")
    private String serverPort;
    //对于注册进eureka里面的微服务，可以通过服务发现来获得该服务的信息
    @Autowired
    private DiscoveryClient discoveryClient;

    @PostMapping(value = "/payment/create")
    public CommonResult<Payment> addPayment(@RequestBody Payment payment,HttpServletRequest req) {
        String serial = req.getParameter("serial");
        log.warn("serial: "+serial);
        long i =  paymentService.addPayment(payment);
        log.info("插入结果： "+ i);
        if (i > 0){
            return new CommonResult<>(200,"insert to db success， serverPort：　" + serverPort,new Payment(i,payment.getSerial()));
        }
        return new CommonResult<>(500," insert to db error， serverPort：　" + serverPort,new Payment(i,payment.getSerial()));
    }
    @GetMapping (value = "/payment/getPaymentById/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id) {
        int a = 1;
        Payment payment = paymentService.getPaymentById(id);
        if (payment != null)
            return new CommonResult<Payment>(200,"success， serverPort：　" + serverPort,payment);
        return new CommonResult<Payment>(500,"error",payment);
    }

    @GetMapping(value = "/payment/discovery")
    public Object discovery(){
        List<String> services = discoveryClient.getServices();
        for (String service : services){
            log.info("该eureka已注册的service: "+ service);
        }
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        List<ServiceInstance> instance2 = discoveryClient.getInstances("CLOUD-CONSUMER-ORDER80");
        for (ServiceInstance instance :instances){
            log.info(instance.getServiceId() +"\t"+instance.getHost()+"\t"+ instance.getPort()+"\t"+instance.getUri());
        }
        return this.discoveryClient;
    }
}
